package net.thxjj.netty;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import net.model.device.CmdBean;
import net.model.device.ReportBean;
import net.model.device.ReportParams;
import net.model.deviceresp.DevRespBean;
import net.thxjj.error.ActionType;
import net.thxjj.error.ErrCode;
import net.util.ParameterMap;
import org.apache.commons.lang.StringUtils;

import java.util.logging.Logger;

public class DeviceReportInfoHandler extends HeartBeatBaseChannelInBoundHandler {
    private Logger log = Logger.getLogger(String.valueOf(this.getClass()));

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
        if(!DeviceSocketMap.hasDevice(ctx.channel())){
            ctx.close();
            return;
        }
        try {
            String de = (String)msg;
            ReportBean reportBean =  JSONObject.parseObject(de, ReportBean.class);
            log.info("收到固件信息："+reportBean.toString());

            ReportParams reportParams = reportBean.getParams();
            if(reportParams==null){
                DevRespBean devRespBean =  new DevRespBean(reportBean.getMsgId(), ActionType.ERROR_RESP.getName(), ErrCode.PARAMS_IS_NOT_EXIST_ERROR.getCode(),ErrCode.PARAMS_IS_NOT_EXIST_ERROR.getDescription(),null);
                ctx.writeAndFlush(devRespBean.toString());
                return;
            }

            if(!StringUtils.isBlank(reportParams.getDevTid())){
                //更新固件信息
                ParameterMap parameterMap = new ParameterMap();
                parameterMap.put("device_id",reportParams.getDevTid());
                parameterMap.put("ssid",reportParams.getSSID());
                parameterMap.put("firmware_version",reportParams.getBinVer());
                parameterMap.put("bin_type",reportParams.getBinType());
                deviceService.updateDevBaseInfo(parameterMap);
            }

            DevRespBean devRespBean =  new DevRespBean(reportBean.getMsgId(), ActionType.DEVICE_REPORTINFORESP.getName(), ErrCode.SUCCESS.getCode(),ErrCode.SUCCESS.getDescription(),null);
            ctx.writeAndFlush(devRespBean.toString());
        }catch (JSONException e){
            e.printStackTrace();
            ctx.close();
        }

    }
}
